package com.example.tnot.Student;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Looper;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.tnot.R;
import com.example.tnot.api.JpegFrameDecoder;
import com.example.tnot.api.SocketClient;
import com.example.tnot.api.VideoDecoder;


public class StudentLiveActivity extends AppCompatActivity implements SocketClient.StudentLiveListener {
    private static final String TAG = "StudentLiveActivity";
    private ImageView liveImageView;
    private TextView roomIdInfoTv;
    private TextView viewerCountTv;
    private Button exitBtn;
    private SocketClient socketClient;
    private VideoDecoder videoDecoder;
    private String currentRoomId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_student_live);

        // 获取从首页传递的房间ID
        currentRoomId = getIntent().getStringExtra("ROOM_ID");
        if (currentRoomId == null || currentRoomId.isEmpty()) {
            Toast.makeText(this, "房间ID不能为空", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 初始化视图
        initViews();

        // 初始化Socket和解码器
        socketClient = SocketClient.getInstance();
        videoDecoder = new VideoDecoder(liveImageView);

        // 连接服务器并加入房间
        connectAndJoinRoom();
    }

    private void initViews() {
        liveImageView = findViewById(R.id.live_image_view);
        roomIdInfoTv = findViewById(R.id.room_id_info);
        viewerCountTv = findViewById(R.id.viewer_count);
        exitBtn = findViewById(R.id.exit_btn);

        roomIdInfoTv.setText("房间ID: " + currentRoomId);

        exitBtn.setOnClickListener(v -> {
            leaveRoomAndFinish();
        });
    }

    private void connectAndJoinRoom() {
        // 连接服务器
        if (!socketClient.getmSocket()) {
            socketClient.connect();
        }

        // 设置监听器
        socketClient.setStudentLiveListener(this);

        // 学生身份连接
        socketClient.studentConnect();

        // 修复：使用带Looper参数的Handler构造方法
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            if (socketClient.getmSocket()) { // 补充连接状态判断
                socketClient.joinLiveRoom(currentRoomId);
                Toast.makeText(this, "正在加入房间...", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "连接服务器失败", Toast.LENGTH_SHORT).show();
                finish();
            }
        }, 1000);
    }

    @Override
    public void onReceiveFrame(byte[] frameData) {
        Log.d(TAG, "收到视频帧数据，长度: " + frameData.length);
        // 解码并显示视频帧
        if (videoDecoder != null) {
            videoDecoder.decodeAndShow(frameData);
        }
    }

    @Override
    public void onError(String message) {
        runOnUiThread(() -> {
            Toast.makeText(this, "错误: " + message, Toast.LENGTH_SHORT).show();
        });
    }

    @Override
    public void onViewerCountChanged(int count) {
        runOnUiThread(() -> {
            viewerCountTv.setText("观众: " + count + "人");
        });
    }

    @Override
    public void onRoomClosed() {
        runOnUiThread(() -> {
            Toast.makeText(this, "直播已结束", Toast.LENGTH_SHORT).show();
            finish();
        });
    }

    @Override
    public void onRoomStatusChanged(String status) {
        runOnUiThread(() -> {
            String statusMsg;
            // 替换增强switch为传统switch
            switch (status) {
                case "started":
                    statusMsg = "直播已开始";
                    break;
                case "paused":
                    statusMsg = "直播已暂停";
                    break;
                case "ended":
                    statusMsg = "直播已结束";
                    break;
                default:
                    statusMsg = "状态更新: " + status;
                    break;
            }
            Toast.makeText(this, statusMsg, Toast.LENGTH_SHORT).show();
        });
    }

    private void leaveRoomAndFinish() {
        if (currentRoomId != null) {
            socketClient.leaveLiveRoom(currentRoomId);
        }
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放资源
        if (videoDecoder != null) {
            videoDecoder.release();
        }
        // 移除监听器，避免内存泄漏
        socketClient.setStudentLiveListener(null);
    }
}